#!/usr/bin/env python
# coding=utf-8
"""WTFM"""
import argparse
import hashlib
import hmac
import base64
import random
import string
from sendmail import sendText
from MysqlUtil import insert, commit

salt = "its a very secret string"

SQL = """INSERT INTO `extrauth_user`(`user_name`, `passwd`, `is_admin`, `groups`)
   VALUES ("{user_name}","{password}",{is_admin},"{groups}");"""


def genSql(user_name, raw_password, is_admin, groups):
    password = make_digest(raw_password, salt)
    if is_admin:
        is_admin_int = 1
    else:
        is_admin_int = 0

    return SQL.format(user_name=user_name, password=password, is_admin=is_admin_int, groups=groups)


def make_digest(message, key):
    key = bytes(key, 'UTF-8')
    message = bytes(message, 'UTF-8')
    digester = hmac.new(key, message, hashlib.sha1)
    signature1 = digester.digest()
    signature2 = base64.b64encode(signature1)

    return str(signature2, 'UTF-8')


def randomword(length):
    letters = string.ascii_lowercase + string.digits
    return ''.join(random.choice(letters) for i in range(length))


if __name__ == '__main__':
    arg_parser = argparse.ArgumentParser(
        description="用于生成一条extrauth用户的sql语句")

    arg_parser.add_argument("user_name")
    arg_parser.add_argument("groups", default="|default|", help="|default|dmp|insight|")
    arg_parser.add_argument("--password")
    arg_parser.add_argument("--admin", default=False, action='store_true')

    args = arg_parser.parse_args()

    password = args.password
    if not password:
        password = randomword(8)

    sql = genSql(args.user_name, password, args.admin, args.groups)
    print(sql)

    xx = insert(sql)
    commit()
    print(xx)
    print(password)

    sendText(args.user_name, "extrauth account create",
             "create account in extrauth h31. auth groups: " + args.groups + ". login by email and pass: " + password)
